﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ComponentModel;

namespace SplitCode
{
    public class RetObj
    {
        public bool isOK = true;
        public string msg = String.Empty;

        public override string ToString()
        {
            if (isOK)
                return "Done.";
            else
                return "Error: " + msg;
        }
    }

    public enum OutputType { TIF, JPG, PDF };

    public delegate void UpdateProgress(int percentDone);

    public class TiffSplitCode
    {
        private static ICoder _coder;

        public static RetObj Prepare(ConfObj input, out int numOfPages)
        {
            RetObj retobj = new RetObj();
            numOfPages = 0;

            if (!File.Exists(input.inputFile))
            {
                retobj.msg = "Input file doesn't exist.";
                retobj.isOK = false;
                return retobj;
            }

            string ext = Path.GetExtension(input.inputFile);
            if (!(ext.ToUpper() == ".TIFF" ||
                ext.ToUpper() == ".TIF" || ext.ToUpper() == ".PDF"))
            {
                retobj.msg = "Input file should have TIF, TIFF or PDF extension.";
                retobj.isOK = false;
                return retobj;
            }

            // overwrite output type if the input is PDF
            if (ext.ToUpper() == ".PDF")
                input.outputType = OutputType.PDF;

            // create output coder
            _coder = CoderFactory(input.outputType);

            // open file
            numOfPages = _coder.LoadImage(input.inputFile);

            // prepare
            _coder.Prepare(input);

            return retobj;
        }

        public static RetObj Split(ConfObj input, UpdateProgress updateProgress)
        {
            int numOfPages = input.toPage - input.fromPage + 1;                               
            // save each image
            for (int i = 0; i < numOfPages; i++)
            {
                _coder.Save(input.fromPage - 1 + i);

                updateProgress((int)Math.Round((double)(i + 1) / (double)numOfPages * 100));
            }

            _coder.Close();

            return new RetObj();
        }

        static private ICoder CoderFactory(OutputType type)
        {
            switch (type)
            {
                case OutputType.TIF:
                    return new TiffCoder();
                case OutputType.JPG:
                    return new JpegCoder();
                case OutputType.PDF:
                    return new PDFCoder();
                default:
                    throw new Exception("Unknown output format.");
            }
        }

       
    }

}
